﻿using ConfExpert.Enums;
using DevTeam;
using System;
using System.Data;
using System.IO;

namespace ConfExpert.Forms.Sistem.Conversion
{
    public static class _7cBarkod
    {

        public static DataTable Convert(ProcessMethod Method, string Path)
        {
            idx = 0;
            CaptionsOK = false;
            DataTable dtSablon = new DataTable();
            dtSablon.Columns.Add("idx", typeof(int));
            dtSablon.Columns.Add("DosyaAdi", typeof(String));

            if (Method == ProcessMethod.XlsFolder)
                foreach (string fileName in Directory.GetFiles(Path, "*.xls", SearchOption.AllDirectories))
                    ProcessOne(dtSablon, fileName);

            return dtSablon;
        }

        static int idx;
        static bool CaptionsOK;
        private static void ProcessOne(DataTable dtSablon, string fileName)
        {
            //FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read);
            //IExcelDataReader excel = ExcelReaderFactory.CreateBinaryReader(stream);
            //DataTable dt = excel.AsDataSet().Tables[0];

            SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook(fileName);
            System.Data.DataSet dataSet = workbook.GetDataSet(SpreadsheetGear.Data.GetDataFlags.NoColumnHeaders);
            DataTable dt = dataSet.Tables[0];

            if (!CaptionsOK)
            {
                for (int colIndex = 0; colIndex < dt.Columns.Count; colIndex++)
                {
                    string cellValue = dt.Rows[0][colIndex].ToStr();

                    if (cellValue != string.Empty)
                        dtSablon.Columns.Add(cellValue, typeof(string));
                }

                CaptionsOK = true;
            }

            string str = string.Empty;

            for (int rowIndex = 0; rowIndex < dt.Rows.Count; rowIndex++)
            {
                if (rowIndex == 0)
                    continue;

                string firstColumnCell = dt.Rows[rowIndex][0].ToStr();
                if (firstColumnCell == string.Empty)
                    break;

                DataRow dr = dtSablon.NewRow();
                dr["DosyaAdi"] = Path.GetFileName(fileName);
                dr["idx"] = ++idx;

                for (int colIndex = 0; colIndex < dt.Columns.Count; colIndex++)
                {
                    string cellValue = dt.Rows[rowIndex][colIndex].ToStr();
                    string label = dt.Rows[0][colIndex].ToString();

                    if (label != string.Empty && cellValue != string.Empty)
                        dr[label] = cellValue;
                }

                dtSablon.Rows.Add(dr);
            }
        }
    }
}
